package matheus.tp01cg;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * View onde esta contido o canvas.
 */
public class AreaDeDesenho extends SurfaceView implements
		SurfaceHolder.Callback {
	private CanvasThread canvasthread;

	public AreaDeDesenho(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		inicializa();
	}

	public AreaDeDesenho(Context context) {
		super(context);
		inicializa();
	}

	public AreaDeDesenho(Context context, AttributeSet attr) {
		super(context, attr);
		inicializa();
	}

	private void inicializa() {
		getHolder().addCallback(this);
		canvasthread = new CanvasThread(getHolder(), this);
		setFocusable(true);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	public void surfaceCreated(SurfaceHolder holder) {
		if (!canvasthread.isRunning()) {
			canvasthread.setRunning(true);
			canvasthread.start();
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean tentarNovamente = true;
		canvasthread.setRunning(false);
		while (tentarNovamente) {
			try {
				canvasthread.join();
				tentarNovamente = false;
			} catch (InterruptedException e) {
				// tenta ateh conseguir
			}
		}
		Log.v(null, "saiu");
	}

	public Bitmap bitmap;

	public Bitmap bitmapDesenhoInterativo = null;

	public int corDeFundo = Color.WHITE;

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawColor(corDeFundo);
		synchronized (bitmap) {
			canvas.drawBitmap(bitmap, 0, 0, null);
		}
		try {
			if (bitmapDesenhoInterativo != null) {
				synchronized (bitmapDesenhoInterativo) {
					canvas.drawBitmap(bitmapDesenhoInterativo, 0, 0, null);
				}
			}
		} catch (Exception e) {
			Log.d(null, e.getClass() + " : " + getClass() + ".onDraw()", e);
		}
	}
}
